package com.dld.coupon.view;

import java.io.ByteArrayInputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.constant.net.Constant;
import com.dld.android.net.Param;
import com.dld.android.persistent.SharePersistent;
import com.dld.coupon.activity.ActivityManager;
import com.dld.coupon.activity.R;
import com.dld.coupon.activity.StoreDetail;
import com.dld.coupon.util.MapUtil;
import com.dld.coupon.util.StringUtils;
import com.dld.protocol.json.AllResult;
import com.dld.protocol.json.Coupon;
import com.dld.protocol.json.CouponDetail;
import com.dld.protocol.json.PageInfo;
import com.dld.protocol.json.Protocol;

public class AllLinearLayout extends ListTab implements MainViewBase {
	static final TypeImage[] TYPE_IMAGES;
	protected ListViewAdapter adapter;
	Handler handler = new Handler();
	protected boolean isFirst = true;
	private String lastUrl = "";
	private double lat = 0.0D;
	protected DownloadListView list;
	private double lng = 0.0D;
	private ProtocolCreator protocolCreator;
	private AllResult result = new AllResult();
	private int category;
	private String keyword;
	private String searchtype;
	private Coupon coupon = new Coupon();

	static {
		TypeImage[] arrayOfTypeImage = new TypeImage[4];
		arrayOfTypeImage[1] = new TypeImage(R.drawable.search_all_type_1, "打折");
		arrayOfTypeImage[2] = new TypeImage(R.drawable.search_all_type_2, "街店");
		TYPE_IMAGES = arrayOfTypeImage;
	}

	public AllLinearLayout(Context paramContext, AttributeSet paramAttributeSet) {
		super(paramContext, paramAttributeSet);
	}

	private void initRefresh() {
		findViewById(R.id.refresh).setOnClickListener(
				new View.OnClickListener() {
					public void onClick(View paramView) {
						AllLinearLayout.this.request(true, MapUtil.getCityId());
						AllLinearLayout.this.adapter.notifyDownload();
					}
				});
	}

	protected AdapterView.OnItemClickListener getItemClickListener() {
		return new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> paramAdapterView,
					View paramView, int paramInt, long paramLong) {
				CouponDetail cd = (CouponDetail) paramView.getTag();
				Intent it = new Intent();
				((Intent) it).setClass(ActivityManager.getCurrent(),
						StoreDetail.class);
				it.putExtra(Constant.CONSTANT_SHOPID, cd.getShopid());
				ActivityManager.getCurrent().startActivity(it);
			}
		};
	}

	protected void init() {
		init(this.protocolCreator, null, false, 100);
	}

	protected void init(ProtocolCreator paramProtocolCreator,
			String paramString, boolean paramBoolean, int category) {
		if (paramProtocolCreator != null)
			this.protocolCreator = paramProtocolCreator;
		this.list = ((DownloadListView) findViewById(R.id.listview));
		this.list.setOnItemClickListener(getItemClickListener());
		int viewtype = this.searchtype.equals("1") ? Constant.VIEW_COUPON
				: Constant.VIEW_STORE;
		this.adapter = new ListViewAdapter(this.searchtype.equals("1") ? true
				: false, list, coupon, viewtype);
		this.list.setAdapter(this.adapter);
		initAddressList(paramString, paramBoolean);
		initCategoryList(category);
		initRefresh();
		this.pageIndex = 1;
		request(false, MapUtil.getCityId());
	}

	public void onHide() {
		this.showing = false;
		hideList();
	}

	public void onShow() {
		show(null, null, false, 0, this.searchtype, this.keyword);
	}

	protected void request() {
		AllLinearLayout.this.adapter.notifyDownload();
		request(true, MapUtil.getCityId());
	}

	protected void request(boolean isFresh, String cityid) {

		try {
			if (isFresh) {
				this.pageIndex = 1;
				AllLinearLayout.this.coupon.details.clear();
				// AllLinearLayout.this.adapter.notifyDownload();
			}
			// String cityid = MapUtil.getCityId();
			Log.v("", "request **************     " + cityid);
			Param param = new Param();
			param.append("userAgent", "dld_android");
			if (keyword != null) {
				param.append("r", "www/api/search");
				param.append("keyword", keyword);
				param.append("areaCode", cityid);
				param.append("categoryCode", "" + super.category.code);
				param.append("searchType", "" + searchtype);
			} else {
				param.append("r", "www/api/list");
				param.append("module", "around");
				param.append("areaCode", cityid);
				param.append("categoryCode", "" + super.category.code);
				param.append("viewType", "2");
			}
			param.append("pageSize", "10");
			param.append("currentPage", "" + this.pageIndex);
			Protocol localProtocol = this.protocolCreator.createProtocol(param);
			localProtocol.startTrans(new AllProtocolResult(String.class));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void show(ProtocolCreator paramProtocolCreator, String paramString,
			boolean paramBoolean, int category, String type, String keyword) {
		this.showing = true;
		String str = SharePersistent.getInstance().getPerference(this.activity,
				"city_id");
		this.category = category;
		this.searchtype = type;
		this.keyword = keyword;
		if (!this.isFirst) {
			if ((StringUtils.isEmpty(this.cityId)) || (this.cityId.equals(str))) {
				if (StringUtils.isEmpty(str)) {
					SharePersistent.getInstance().getPerference(this.activity,
							"city_id");
					this.pageIndex = 0;
					request();
				}
			} else
				init(paramProtocolCreator, paramString, paramBoolean, category);
		} else {
			init(paramProtocolCreator, paramString, paramBoolean, category);
			this.isFirst = false;
		}
	}

	protected class AllProtocolResult extends Protocol.OnJsonProtocolResult {
		public AllProtocolResult() {
			super();
		}

		public AllProtocolResult(Class cls) {
			super(cls);
		}

		private void notifyException() {
			AllLinearLayout.this.handler.post(new Runnable() {
				public void run() {
					AllLinearLayout.this.adapter.notifyNoResult();
				}
			});
		}

		public void onException(String paramString, Exception paramException) {
			notifyException();
		}

		public void onResult(String paramString, final Object paramObject) {

			AllLinearLayout.this.activity.runOnUiThread(new Runnable() {
				public void run() {
					try {
						String content = (String) paramObject;
						Element root = DocumentBuilderFactory.newInstance()
								.newDocumentBuilder().parse(
										new ByteArrayInputStream(content
												.getBytes()))
								.getDocumentElement();
						List<CouponDetail> nlist = CouponDetail
								.fromXmlToAdroundInfo(root);
						AllLinearLayout.this.coupon.details.addAll(nlist);
						try {
							NodeList lsittotal = root
									.getElementsByTagName("total");
							String total = lsittotal.item(0).getFirstChild()
									.getNodeValue();
							PageInfo pinfo = new PageInfo();
							pinfo.total = Integer.parseInt(total);
							AllLinearLayout.this.coupon.pageInfo = pinfo;
							if (pinfo.total > 0) {
								AllLinearLayout.this.adapter
										.notifyDownloadBack();
							} else {
								AllLinearLayout.this.adapter.notifyNoResult();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			});
		}
	}

	private class ListViewAdapter extends CouponDownLoadAdapter {

		public ListViewAdapter(boolean paramBoolean,
				DownloadListView paramDownloadListView, Coupon paramCoupon,
				int view_type) {
			super(paramBoolean, paramDownloadListView, paramCoupon, view_type);
		}

		@Override
		public Context getContext() {
			return AllLinearLayout.this.getContext();
		}

		@Override
		public void onNotifyDownload() {
			AllLinearLayout.this.pageIndex++;
			request(false, MapUtil.getCityId());
		}

	}

	public static abstract interface ProtocolCreator {
		public abstract Protocol createProtocol(Param param);
	}

	static final class TypeImage {
		int image;
		String text;

		TypeImage(int paramInt, String paramString) {
			this.image = paramInt;
			this.text = paramString;
		}
	}

	@Override
	protected void requestBy(String cityid) {
		AllLinearLayout.this.adapter.notifyDownload();
		request(true, cityid);
	}
}
